<template>
  <el-dialog
    v-model="dialogVisible"
    v-if="load"
    :title="title"
    width="1100"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="handleClose"
    @close="close"
    :z-index="2000"
  >
    <div>
      <template v-if="spuArr && spuArr?.length">
        <el-tabs type="border-card">
          <el-tab-pane
            class="relative"
            :label="item.custom_sku"
            v-for="(item, index) in spuArr"
            :key="index"
          >
            <template #label>
              {{ item.sku || item.custom_sku }}
            </template>
            <div class="flex">
              <div class="flex-1">
                <div style="font-weight: 700">产品信息</div>
                <i class="border-solid" />
                <div class="h-t w-[800px]">
                  <div class="updateMar">
                    <span class="updateTitle">产品分类：</span
                    ><span class="updateTitleLevel">{{
                      item.goods_spu?.spu_category_text
                    }}</span>
                  </div>
                  <div class="updateMar">
                    <span class="updateTitle">产品名称：</span
                    ><span class="updateTitleLevel">{{ item.sku_cn_title }}</span>
                  </div>
                  <div class="updateMar clearfix">
                    <div class="fl">
                      <span class="updateTitle">SPU：</span
                      ><span class="updateTitleLevel">{{ item.spu }}</span>
                    </div>
                    <div class="fl" style="margin: 0 43px 0 73px">
                      <span class="updateTitle">SKU：</span
                      ><span class="updateTitleLevel" style="color: #3366f1">{{
                        item.sku
                      }}</span>
                    </div>
                    <div class="fl">
                      <span class="updateTitle">自定义SKU：</span
                      ><span class="updateTitleLevel" style="color: #3366f1">{{
                        item.custom_sku || "--"
                      }}</span>
                    </div>
                  </div>
                </div>
              </div>
              <div class="w-[100px] h-[100px] mt-2" @click="showImage(item.sku_id)">
                <img
                  class="w-full h-full object-cover"
                  :src="item.attr_img_watermark || item.attr_img"
                />
              </div>
            </div>

            <div class="updateMar clearfix jf">
              <div class="fl">
                <span class="updateTitle"
                  >品牌：{{ item.goods_sku_sales_info?.brand_name || "--" }}</span
                >
              </div>
              <div class="fl">
                <span class="updateTitle"
                  >规格型号：{{ item.goods_spu?.specification_model || "--" }}</span
                >
                <!-- 暂无此字段 -->
              </div>
              <div class="fl">
                <span class="updateTitle"
                  >插头规格：{{
                    item.goods_sku_sales_info?.plug_specification_text || "--"
                  }}</span
                >
                <!-- 暂无此字段 -->
              </div>
              <div class="fl">
                <span class="updateTitle">产品多属性：</span
                ><span class="updateTitleLevel">{{
                  item.sku_specification?.header.length >= 2 ? "多属性" : "单属性"
                }}</span>
              </div>
            </div>
            <div class="updateMar clearfix jf">
              <div class="fl">
                <span class="updateTitle"
                  >物流属性：{{ item.goods_spu?.logistics_attributes_name }}</span
                >
              </div>
              <div class="fl">
                <span class="updateTitle">是否需要加工：</span
                ><span class="updateTitleLevel">{{
                  item.goods_spu?.need_processing_text
                }}</span>
              </div>
              <div class="fl">
                <span class="updateTitle">报关材质：</span>
                <span class="updateTitleLevel" v-if="item.goods_sku_supplier">{{
                  getCNMaterial(item.goods_sku_supplier)
                }}</span>
              </div>
              <div class="fl">
                <span class="updateTitle">是否含有辅料：</span>
                <span class="updateTitleLevel">{{
                  item.is_contains_accessories == 1 ? "是" : "否"
                }}</span>
              </div>
            </div>
            <div class="updateMar clearfix jf">
              <div class="fl">
                <span class="updateTitle">产品毛重(g)：</span
                ><span class="updateTitleLevel">{{ item.gross_weight_g }}</span>
              </div>
              <div class="fl">
                <span class="updateTitle">产品净重(g)：</span
                ><span class="updateTitleLevel">{{ item.net_weight_g }}</span>
              </div>
              <div class="fl">
                <span class="updateTitle">产品尺寸：</span
                ><span class="updateTitleLevel">
                  {{ item.product_size_cm?.length }}*{{ item.product_size_cm?.width }}*{{
                    item.product_size_cm?.height
                  }}cm
                </span>
              </div>
              <div class="fl">
                <span class="updateTitle" style="white-space: nowrap"
                  >产品包装尺寸：</span
                >
                <span class="updateTitleLevel"
                  >{{ item.packing_size_cm?.length }}*{{ item.packing_size_cm?.width }}*{{
                    item.packing_size_cm?.height
                  }}cm</span
                >
              </div>
            </div>
            <div class="updateMar clearfix jf">
              <div class="fl">
                <span class="updateTitle">认证类型：</span
                ><span class="updateTitleLevel">{{
                  filterAuth(item.goods_sku_authentication)
                }}</span>
              </div>
              <div class="fl">
                <span class="updateTitle">开发人员：</span
                ><span class="updateTitleLevel">{{ item.developer_text }}</span>
              </div>
              <div class="fl">
                <span class="updateTitle">证书/文件：</span
                ><span
                  class="cursor-pointer text-[#3366f1]"
                  @click="showCertificateInformation(item.sku_id)"
                  >点击查看</span
                >
              </div>
            </div>
            <div
              style="
                font-weight: 700;
                height: 44px;
                line-height: 44px;
                border-radius: 8px 8px 0px 0px;
                border: 1px solid #e6e7e9;
                margin-bottom: -1px;
                margin-top: 8px;
                padding-left: 10px;
              "
            >
              编辑备注
            </div>
            <div
              class="radius"
              style="border: 1px solid #e6e7e9; margin-top: -1px; padding: 10px"
            >
              <template v-if="item.edit_remark">
                <div v-html="item.edit_remark"></div>
              </template>
              <div class="text-[#999]" v-else>暂无备注</div>
            </div>
            <div
              style="
                font-weight: 700;
                height: 44px;
                line-height: 44px;
                border-radius: 8px 8px 0px 0px;
                border: 1px solid #e6e7e9;
                margin-bottom: -1px;
                margin-top: 8px;
                padding-left: 10px;
              "
            >
              重点检测事件
            </div>
            <div
              v-if="item.inspection_items?.length"
              :class="idx == item.inspection_items?.length - 1 ? 'radius' : ''"
              style="border: 1px solid #e6e7e9; margin-top: -1px; padding-left: 10px"
              v-for="(i, idx) of item.inspection_items"
              :key="idx"
            >
              <div class="flex items-center py-4">
                <div class="mr-2">
                  <el-select
                    v-model="i.item_id"
                    collapse-tags
                    placeholder="请选择"
                    clearable
                    style="width: 148px"
                    @change="changeInspection($event, item)"
                    :disabled="handleType == 'view'"
                  >
                    <el-option
                      v-for="k in options['sample.SampleSku']?.[0].inspectionItemsText"
                      :key="k.value"
                      :label="k.label"
                      :value="k.value"
                    />
                  </el-select>
                </div>
                <div :style="{ marginRight: !isDetection ? '30px' : '' }">
                  <el-input
                    v-model="i.item_content"
                    placeholder="请输入"
                    style="width: 650px"
                    :disabled="handleType == 'view'"
                  />
                </div>
                <div class="flex" v-if="isDetection && handleType != 'view'">
                  <svg-icon
                    class="text-xl ml-2"
                    icon-class="jian"
                    @click="inspectionItemsReduce(index, idx)"
                    v-if="idx != 0"
                  ></svg-icon>

                  <svg-icon
                    class="text-xl ml-2"
                    icon-class="add"
                    @click="inspectionItemsAdd(index, idx)"
                  ></svg-icon>
                </div>
              </div>
            </div>
            <div
              style="
                font-weight: 700;
                height: 44px;
                line-height: 44px;
                border-radius: 8px 8px 0px 0px;
                border: 1px solid #e6e7e9;
                margin-bottom: -1px;
                margin-top: 16px;
                padding-left: 10px;
              "
            >
              检测问题点
            </div>
            <div class="border py-4 px-4">
              <template v-if="handleType == 'view'">
                <template v-if="item.problem_points">
                  <div v-html="item.problem_points"></div>
                </template>
                <div class="text-[#999]" v-else>暂无检测问题点</div>
              </template>
              <template v-else>
                <WangEditor v-model="item.problem_points" :min-height="100" />
              </template>
            </div>

            <div
              style="
                font-weight: 700;
                height: 44px;
                line-height: 44px;
                border-radius: 8px 8px 0px 0px;
                border: 1px solid #e6e7e9;
                margin-bottom: -1px;
                margin-top: 16px;
                padding-left: 10px;
              "
            >
              仓库质检备注
            </div>
            <div class="border px-4 py-4">
              <template v-if="handleType == 'view'">
                <template v-if="item.warehouse_inspection_report">
                  <div v-html="item.warehouse_inspection_report"></div>
                </template>
                <div class="text-[#999]" v-else>暂无仓库质检备注</div>
              </template>
              <template v-else>
                <WangEditor
                  v-model="item.warehouse_inspection_report"
                  :min-height="100"
                />
              </template>
            </div>
            <div style="margin-top: 10px">
              <span style="font-size: 14px; font-weight: 700">附件</span>
              <template v-if="handleType === 'view'">
                <div v-if="item.warehouse_report_url.length">
                  {{ item.warehouse_report_url[0] }}
                  <el-link
                    type="primary"
                    :underline="false"
                    @click="downloadUrl(item.warehouse_report_url)"
                    >下载
                  </el-link>
                </div>
                <div class="text-[#999]" v-else>暂无附件</div>
              </template>
              <template v-else>
                <FileUpload v-model:files="item.warehouse_report_url"></FileUpload>
              </template>
            </div>
            <div
              style="
                font-weight: 700;
                height: 44px;
                line-height: 44px;
                border-radius: 8px 8px 0px 0px;
                border: 1px solid #e6e7e9;
                margin-bottom: -1px;
                padding-left: 10px;
              "
            >
              检测结果
            </div>
            <div
              class="px-4 py-4"
              style="
                border-radius: 0px 0px 8px 8px;
                border: 1px solid #e6e7e9;
                margin-top: -1px;
                padding-left: 10px;
              "
            >
              <template v-if="handleType == 'view'">
                <div class="text-center">
                  <div class="flex justify-center items-center text-base">
                    <svg-icon
                      v-if="!item.detection_status"
                      class="text-green-500 text-base mr-2"
                      :icon-class="
                        item.detection_status == 1
                          ? 'state_finish_cover2'
                          : 'state_finish_cover'
                      "
                    ></svg-icon>
                    {{
                      item.detection_status === 1
                        ? "正常"
                        : item.detection_status === 2
                        ? "不通过"
                        : "待检测"
                    }}
                  </div>
                  <div class="text-gray-500" v-if="item.detection_status">
                    SKU样品检测结果
                  </div>
                  <div v-if="item.detection_report_url.length">
                    {{ item.detection_report_url[0] }}
                    <el-link
                      type="primary"
                      :underline="false"
                      @click="downloadUrl(item.detection_report_url)"
                      >下载</el-link
                    >
                  </div>
                </div>
              </template>
              <template v-else>
                <div class="py-2" style="font-size: 14px; font-weight: 700">
                  SKU样品检测结果<span style="color: red">*</span>
                </div>
                <el-select
                  class="w-full"
                  v-model="item.detection_status"
                  collapse-tags
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="item in statesText2"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <div style="margin-top: 10px; margin-bottom: 24px">
                  <span style="font-size: 14px; font-weight: 700">附件</span>
                  <FileUpload v-model:files="item.detection_report_url"></FileUpload>
                </div>
              </template>
            </div>
          </el-tab-pane>
        </el-tabs>
      </template>
      <template v-else>暂无数据</template>
    </div>
    <template #footer>
      <div class="flex justify-center items-center py-4" v-if="handleType == 'view'">
        <el-button @click="handleCancel">关闭</el-button>
      </div>
      <div class="flex justify-center items-center py-4" v-else>
        <el-checkbox
          class="mr-2"
          v-model="is_auditing"
          :true-label="1"
          :false-label="0"
          size="large"
          >同步开发审核</el-checkbox
        >
        <el-tooltip placement="top">
          <template #content>
            说明<br />1、只针对产品开发审核人=质检人员情况；质检通过or未通过，<br />同步开发审核通过or审核未通过。请根据实际情况勾选。
          </template>
          <svg-icon icon-class="hint_line"></svg-icon>
        </el-tooltip>
        <el-button class="ml-4" @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="serveFun"> 保存 </el-button>
        <div class="flex items-center ml-4">
          消息通知：
          <el-checkbox v-model="is_notice" :true-label="1" :false-label="0" size="large"
            >运营人员</el-checkbox
          >
          <el-checkbox
            v-model="is_developer_notice"
            :true-label="1"
            :false-label="0"
            size="large"
            >开发人员</el-checkbox
          >
        </div>
      </div>
    </template>
  </el-dialog>
  <CertificateInformation ref="CertificateInformationRef"></CertificateInformation>
  <checkImage ref="checkImageRef"></checkImage>
</template>

<script setup lang="jsx">
import FileUpload from "./FileUpload.vue";
import { onMounted, ref, reactive, toRefs } from "vue";
import WangEditor from "@/components/WangEditor/index.vue";
import { uploadInspectionReport, getInspectionReport, querySkuList } from "../api";
import { ElMessage, ElMessageBox } from "element-plus";
import CertificateInformation from "@/components/CertificateInformation/index";
import checkImage from "./checkImage.vue";
import { pushsaihe } from "@/api/index";
import { getSKUDetailList } from "@/api/index.js";

const dialogVisible = ref(false);

const inspectionItemsAdd = (index, idx) => {
  spuArr.value[index].inspection_items.push({
    item_id: "",
    item_name: "",
    item_content: "",
  });
};
const inspectionItemsReduce = (index, idx) => {
  spuArr.value[index].inspection_items.splice(idx, 1);
};

const statesText2 = ref([
  {
    value: 1,
    label: "通过",
  },
  {
    value: 2,
    label: "未通过",
  },
]);
const spuArr = ref({});

const clearForm = () => {
  spuArr.value = [];
};

const handleCancel = () => {
  clearForm();
  dialogVisible.value = false;
};

const serveFun = () => {
  const product_list = spuArr.value.map((i) => {
    return {
      id: i.id,
      goods_sku: i.sku,
      spu_id: i.spu_id,
      problem_points: i.problem_points,
      inspection_items: i.inspection_items,
      detection_report_url: i.detection_report_url.join(","),
      detection_status: i.detection_status || "",
      warehouse_inspection_report: i.warehouse_inspection_report,
      warehouse_report_url: i.warehouse_report_url.join(","),
    };
  });

  let massageArray = [];
  product_list.length &&
    product_list.forEach((item, index) => {
      if (item.detection_status === "") {
        massageArray.push(`请选择第 ${index + 1}项 ${item.goods_sku}SKU样品检测结果`);
      }
    });
  if (massageArray && massageArray.length) {
    ElMessageBox({
      title: "提示",
      message: () => <div>{massageArray.map((d) => h("p", null, d))}</div>,
    });
    return;
  }

  // 仓库质检备注有值，且赛盒SKU有值，则需触发‘推送赛盒’
  // const is_flag = product_list.some((i) => {
  //   return (
  //     i.warehouse_inspection_report &&
  //     i.warehouse_inspection_report != "<p><br></p>" &&
  //     i.goods_sku
  //   );
  // });

  uploadInspectionReport({
    sample_order_num: sampleOrderNum.value, // YP230512975  用这个单号即可通过 测试用
    product_list: product_list,
    is_notice: is_notice.value,
    is_auditing: is_auditing.value,
    is_developer_notice: is_developer_notice.value,
  }).then((res) => {
    ElMessage.success("操作成功");
    emits("query");
    dialogVisible.value = false;
    // if (is_flag) {
    //   handlePush(product_list[0].spu_id);
    // }
  });
};

// 推送赛盒
const handlePush = async (spu_id) => {
  try {
    const res = await pushsaihe({
      spu_id,
    });
    ElMessage.success(res.message);
  } catch (e) {
    throw Error(e);
  }
};

onMounted(() => {});
const handleClose = (done) => {
  done();
};

const close = () => {
  spuArr.value = [];
};
const data = reactive({
  sampleOrderNum: null,
  goods_sku: null,
  sample_id: null,
  handleType: "",
  title: "",
  is_notice: 0,
  is_auditing: 0,
  is_developer_notice: 0,
  load: false,
});

const statusMap = new Map([
  ["add", "上传检测报告"],
  ["edit", "编辑检测报告"],
  ["view", "查看检测报告"],
]);

const {
  sampleOrderNum,
  goods_sku,
  sample_id,
  handleType,
  title,
  is_notice,
  is_auditing,
  is_developer_notice,
  load,
} = toRefs(data);
const open = async (item, type) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  sampleOrderNum.value = item.sampleOrderNum;
  goods_sku.value = item.goods_sku;
  sample_id.value = item.sample_id;
  handleType.value = type;
  is_notice.value = item.is_notify_operation;
  is_auditing.value = 0;
  is_developer_notice.value = 0;
  title.value = statusMap.get(type);

  const sku = item.product_list.map((i) => i.goods_sku);

  getInspectionReport({ sample_id: item.sample_id }).then((res) => {
    getSKUDetailList({ sku }).then((res1) => {
      spuArr.value = res1.data.map((i, index) => {
        const item = res.data.find(
          (j) => j.goods_sku == i.sku || j.custom_sku == i.custom_sku
        );
        const sku_id = i.id;
        if (item) {
          return {
            ...item,
            ...i,
            sku_id,
            spu_id: i.spu_id,
            id: item.id,
            inspection_items: item?.inspection_items || [
              {
                item_id: 1,
                item_name: "电子功能件",
                item_content: "",
              },
            ],
            problem_points: item?.problem_points,
            detection_status: item?.detection_status || "",
            warehouse_inspection_report: item?.warehouse_inspection_report || "",
            detection_report_url: item?.detection_report_url
              ? [item?.detection_report_url]
              : [],
            warehouse_report_url: item?.warehouse_report_url
              ? [item?.warehouse_report_url]
              : [],
            goods_sku_authentication: item?.sku_detail?.goods_sku_authentication,
            edit_remark: item?.sku_detail?.goods_sku_remark?.edit_remark,
          };
        }
      });

      console.log(spuArr.value);
    });
  });
  dialogVisible.value = true;
};
const props = defineProps({
  eidtTitle: {
    type: String,
    default: () => "上传检测",
  },
  isDetection: {
    type: Boolean,
    default: () => true,
  },
  options: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const { options } = toRefs(props);

const downloadUrl = (url) => {
  if (!url) {
    return ElMessage.error("下载地址为空，请查看返回数据是否异常！");
  }
  let link = document.createElement("a");
  link.style.display = "none";
  link.href = url;
  link.setAttribute("download", "导出");
  document.body.appendChild(link);
  link.click();
};

const changeInspection = (val, item) => {
  const findItem = options.value["sample.SampleSku"]?.[0].inspectionItemsText.find(
    (i) => i.value == val
  );
  item.item_name = findItem?.label;
};

const emits = defineEmits(["uploadQuery"]); // update:detection is the name of the event to be passed to the parent component.
defineExpose({ open });

// 查看证书文件
const CertificateInformationRef = ref();
const showCertificateInformation = (sku_id) => {
  CertificateInformationRef.value.open(sku_id);
};

// 查看图片
const checkImageRef = ref();
const showImage = (sku_id) => {
  checkImageRef.value.open(sku_id);
};

const filterAuth = (list) => {
  if (!list?.length) {
    return "--";
  }
  let uniqueAuthNames = new Set();

  list.forEach((i) => {
    const country = i.country.map((j) => j.country_name).join("、");
    const text = `【${country}、${i.authentication_name}】`;
    uniqueAuthNames.add(text);
  });

  let text = Array.from(uniqueAuthNames);
  return text.join("、");
};

// 获取报关材质
const getCNMaterial = (list) => {
  if (list?.length == 0) {
    return "--";
  }
  const findItem = list.find((i) => i.is_default_supplier == 1);
  return findItem?.goods_sku_customs?.cn_material || "--";
};
</script>
<style lang="scss" scoped>
.updateTitle {
  color: var(--base-sub-text-color);
  font-size: 14px;
  display: inline-block;
}

.updateMar {
  margin: 16px 0;
}

.updateTitleLevel {
  color: var(--base-text-color);
  font-size: 14px;
}

.border-solid {
  position: absolute;
  left: -15px;
  bottom: 10px;
  width: calc(100% + 15px);
  height: 1px;
  background-color: #e7e8ea;
}

.radius {
  border-radius: 0px 0px 8px 8px;
}

.h-t {
  position: relative;

  > .updateMar {
    padding-right: 100px;

    .fl {
      line-height: 32px;
    }
  }

  .im {
    position: absolute;
    right: 0;
    top: 0;

    img {
      width: 100px;
      height: 100px;
      object-fit: cover;
    }
  }
}

.updateMar.jf {
  color: red;

  .fl {
    width: 25%;
  }
}
</style>
